#!/usr/bin/env python
"""
使用MCP Inspector测试GitCode MCP服务器
"""
import subprocess
import os
import sys
import time
import webbrowser

def main():
    """启动MCP Inspector并打开浏览器"""
    print("准备启动GitCode MCP服务器与Inspector...")
    
    # 确保设置了GitCode令牌
    if not os.environ.get("GITCODE_TOKEN"):
        print("⚠️ 警告: 未设置GITCODE_TOKEN环境变量，某些功能可能无法正常工作")
        print("请设置令牌后重试，例如: export GITCODE_TOKEN=your_token_here")
        should_continue = input("是否继续? (y/n): ").strip().lower()
        if should_continue != 'y':
            print("测试已取消")
            return
    
    # 启动MCP Inspector
    cmd = ["mcp", "dev", "src/gitcode_mcp/server.py"]
    print(f"执行命令: {' '.join(cmd)}")
    
    try:
        # 启动进程
        process = subprocess.Popen(
            cmd,
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
            text=True,
            bufsize=1
        )
        
        # 等待服务器启动
        inspector_url = None
        for i in range(30):  # 等待最多30秒
            if process.poll() is not None:
                # 进程已结束
                break
                
            line = process.stdout.readline().strip()
            if line:
                print(f"服务器输出: {line}")
                
                # 检查是否包含Inspector URL
                if "MCP Inspector is up and running at" in line:
                    inspector_url = line.split("at ")[-1].split(" ")[0].strip()
                    break
            
            time.sleep(1)
            
        if inspector_url:
            print(f"\n🎉 MCP Inspector已成功启动! Inspector界面地址: {inspector_url}")
            print("正在打开浏览器...")
            
            # 打开浏览器
            webbrowser.open(inspector_url)
            
            print("\n💡 测试指南:")
            print("1. 在Inspector界面中，点击'Tools'标签查看可用工具")
            print("2. 在某个工具上点击'Try it'进行测试")
            print("3. 使用'Resources'标签查看可用资源")
            print("4. 使用'Prompts'标签查看可用提示模板")
            print("5. 完成测试后，关闭该终端窗口即可停止服务器")
            
            print("\n按Ctrl+C可随时终止服务器")
            
            # 保持进程运行，直到用户按Ctrl+C
            try:
                process.wait()
            except KeyboardInterrupt:
                print("\n接收到中断信号，正在关闭服务器...")
        else:
            print("❌ MCP Inspector未能成功启动，请检查错误信息")
    
    except Exception as e:
        print(f"❌ 启动MCP Inspector时出错: {e}")
    finally:
        # 确保进程已终止
        if process and process.poll() is None:
            print("正在终止服务器进程...")
            process.terminate()
            try:
                process.wait(timeout=5)
            except subprocess.TimeoutExpired:
                process.kill()
        
        print("测试完成")

if __name__ == "__main__":
    main() 